<template>
  <el-dialog title="在线盖章" top="2%" :visible.sync="dialogVisible" width="100%" append-to-body :before-close="handleClose">
    <div class="avue-dialogs" v-if="loading1">
      <span class="el-icon-loading"></span>
      &nbsp;加载中...
    </div>
    <div id="elesign" class="elesign">
      <el-row>
        <el-col :span="4" style="margin-top: 1.2%;">
          <div>
            <el-upload class="upload-demo" ref="upload231" :headers="uploadHeaders" action="/api/upload/put-file"
              accept=".pdf" :data="{ businessType: 'preparation' }" :before-upload="handlebeforeUpload"
              :on-error="handleError" limit="1" :on-success="handleSuccess" :show-file-list="false">
              <el-button slot="trigger" size="small" type="primary" @click="clickImport()">本地上传</el-button>
            </el-upload>
          </div>


<!--          <div class="left-title">文件信息</div>
          <div>
            <div>
              <div class="right-item">
                <div class="right-item-title">文件主题</div>
                <div class="detail-item-desc">{{ taskInfo.title }}</div>
              </div>
              <div class="right-item">
                <div class="right-item-title">发起方</div>
                <div class="detail-item-desc">{{ taskInfo.uname }}</div>
              </div>
              <div class="right-item">
                <div class="right-item-title">当前时间</div>
                <div class="detail-item-desc">{{ taskInfo.newDate }}</div>
              </div>
            </div>
          </div> -->
        </el-col>
        <el-col :span="16" class="pCenter">
          <div class="page">
            <!-- <el-button class="btn-outline-dark" @click="zoomIn">-</el-button>
            <span style="color: red;"></span>
            <el-button class="btn-outline-dark" @click="zoomOut">+</el-button> -->
            <el-button class="btn-outline-dark" @click="prevPage">上一页</el-button>
            <el-button class="btn-outline-dark" @click="nextPage">下一页</el-button>
            <el-button class="btn-outline-dark">{{ pageNum }}/{{ numPages }}页</el-button>
            <el-input-number style="margin: 0 5px; border-radius: 5px;" class="btn-outline-dark" v-model="pageNum"
              :min="1" :max="numPages" label="输入页码"></el-input-number>
            <el-button class="btn-outline-dark" @click="cutover">跳转</el-button>
          </div>
          <canvas id="the-canvas" />
          <!-- 盖章部分 -->
          <canvas id="ele-canvas"></canvas>
          <div class="ele-control" style="margin-bottom: 2%;">
            <el-button class="btn-outline-dark" @click="removeSignature">
              删除签章</el-button>
            <el-button class="btn-outline-dark" @click="clearSignature">
              清除所有签章</el-button>
            <el-button class="btn-outline-dark" @click="submitSignature">提交所有签章信息</el-button>
          </div>
        </el-col>
        <el-col :span="4" style="margin-top: 1.2%;">
          <div class="left-title">我的印章</div>
          <draggable v-model="mainImagelist" :group="{ name: 'itext', pull: 'clone' }" :sort="false" @end="end">
            <transition-group type="transition">
              <li v-for="item in mainImagelist" :key="item" class="item" style="text-align: center;">
                <img :src="item" width="100%;" height="100%" class="imgstyle" />
              </li>
            </transition-group>
          </draggable>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>
<script>
  import {
    fabric
  } from 'fabric' // 绘制的图形,会检测到边界,多边形按照顺时针或逆时针的顺序放置
  let pdfjsLib = require('pdfjs-dist/legacy/build/pdf.js')
  import workerSrc from 'pdfjs-dist/legacy/build/pdf.worker.entry'
  pdfjsLib.GlobalWorkerOptions.workerSrc = workerSrc
  import draggable from 'vuedraggable' // 拖拽

  import {
    getToken
  } from '@/util/auth'
  import {
    Base64
  } from 'js-base64'
  import website from '@/config/website'

  import {
    requestAvailableSealList,
    requestSealStamp
  } from '@/api/unitReview/approval2.js'

  export default {
    components: {
      draggable
    },
    data() {
      return {
        dialogVisible: true, // 弹窗显/隐、
        loading1:false,
        uploadHeaders: {}, //上传请求头参数
        paraFileList: [], //上传文件数组
        fileUid:0,
        // 上传附件系列参数
        fileList: {
          fileListAssign: [], // 指派的附件默认展示(请严格要求此格式组装数据，谢谢)
          uploadHeaders: {}, // 上传附件的头部的参数
          classifyid: {
            businessType: 'preparation' // 业务类型-传英文
          },
        },

        //pdf预览
        pdfUrl: '',
        pdfDoc: null,
        numPages: 1,
        pageNum: 1,
        // scale: 1.256,
        scale: 1.2,
        pageRendering: false,
        pageNumPending: null,
        sealUrl: '',
        signUrl: '',
        canvas: null,
        ctx: null,
        canvasEle: null,
        whDatas: null,
        mainImagelist: [],  //图片数组
        mainImagelistIdList: [],  //图片数组id
        taskInfo: {}, // 文件信息
        timer: null,
      }
    },
    computed: {
      hasSigna() {
        return this.canvasEle && this.canvasEle.getObjects()[0] ? true : false
      },
    },
    created() {
      let that = this
      // that.mainImagelist = [
      //   'https://attach-huada.sdhuan.cn/water-conservancy-prod/preparation/2023/04/123165a5-734d-421d-908e-1d7357eff97e.jpg',
      // ]
      // that.mainImagelist = [
      //   require('./images/sign.png'),
      //   require('./images/seal.png'),
      // ]
      that.taskInfo = {
        title: '盖章',
        uname: '山东省水利局',
        newDate: '',
      }
      // that.setPdfArea() // 打开pdf
      that.showTimes() // 默认时间

      //请求我的签章
      requestAvailableSealList().then((res) => {
        if (res.data.code === 200) {
          let resData = res.data.data
          resData.forEach(item=>{
            that.mainImagelist.push(item.sealImg)
            that.mainImagelistIdList.push(item.id)
          })
        }
      })

    },

    mounted() {
      this.uploadHeaders = {
        Authorization: `Basic ${Base64.encode(
          `${website.clientId}:${website.clientSecret}`
        )}`,
        'Blade-Auth': 'bearer ' + getToken(),
      }
    },

    beforeDestroy() {
      if (this.timer) {
        clearInterval(this.timer) // 在Vue实例销毁前，清除我们的定时器
      }
    },

    methods: {
      handleClose(){
        this.$emit('handleCloseStamp')
      },

      clickImport() {
        // this.uploadHeaders = {
        //   Authorization: `Basic ${Base64.encode(
        //   `${website.clientId}:${website.clientSecret}`
        // )}`,
        //   'Blade-Auth': 'bearer ' + getToken(),
        // }
      },

      //MARK-上传代理
      // 文件上传之前----------
      handlebeforeUpload(file) {
        this.loading1 = true
        const isSize = file.size / 1024 / 1024 // 文件大小
        if (isSize > 10000000) {
          this.loading1 = false
          this.$message.error(`上传文件大小不能超过 10000000 MB!`);
          return false
        }
        var FileExt = file.name.replace(/.+\./, '')
        let docTypeList = ['pdf']
        let docTypeStr = docTypeList.join(',')
        if (docTypeList.indexOf(FileExt.toLowerCase()) === -1) {
          this.loading1 = false
          let msgTip = '请上传后缀名为' + docTypeStr + '文件！'
          this.$message({
            type: 'error',
            message: msgTip
          })
          return false
        }
        this.loading1 = true
        return true
      },
      // 文件上传成功后---返回
      handleSuccess(res, file) {
        this.$refs.upload231.clearFiles(); //上传成功之后清除历史记录
        localStorage.removeItem('signs') //清除缓存
        this.pageNum = 1 //默认恢复1
        this.clearSignature()
        if (res.code == 200) {
          this.loading1 = false
          let link = res.data.link
          this.fileUid = file.uid
          this.setPdfArea(link)
        } else {
          this.$message.error(res.msg)
        }
        this.loading1 = false
      },

      // 文件上传失败后---返回
      handleError(res) {
        console.log('失败___',res)
        this.loading1 = false
        setTimeout(() => {
          this.$message.error(JSON.parse(res.message).msg)
        }, 1000)
      },

      //pdf预览
      zoomIn() {
        console.log("缩小");
        if (this.scale <= 0.5) {
          this.$message.error("已经显示最小比例")
        } else {
          this.scale -= 0.1;
          this.percentage -= 0.1;
          this.renderPage(this.pageNum);
          this.renderFabric();
        }
      },
      zoomOut() {
        console.log("放大")
        if (this.scale >= 2.2) {
          this.$message.error('已经显示最大比例')
        } else {
          this.scale += 0.1;
          this.percentage += 0.1;
          this.renderPage(this.pageNum);
          this.renderFabric();
        }
      },
      renderPage(num) {
        let _this = this
        this.pageRendering = true
        return this.pdfDoc.getPage(num).then((page) => {
          let viewport = page.getViewport({
            scale: _this.scale
          }) //设置视口大小
          _this.canvas.height = viewport.height
          _this.canvas.width = viewport.width

          // Render PDF page into canvas context
          let renderContext = {
            canvasContext: _this.ctx,
            viewport: viewport,
          }
          let renderTask = page.render(renderContext)
          // Wait for rendering to finish
          renderTask.promise.then(() => {
            _this.pageRendering = false
            if (_this.pageNumPending !== null) {
              // New page rendering is pending
              this.renderPage(_this.pageNumPending)
              _this.pageNumPending = null
            }
          })
        })
      },
      queueRenderPage(num) {
        if (this.pageRendering) {
          this.pageNumPending = num
        } else {
          this.renderPage(num)
        }
      },
      prevPage() {
        this.confirmSignature()
        if (this.pageNum <= 1) {
          return
        }
        this.pageNum--
      },
      nextPage() {
        this.confirmSignature()
        if (this.pageNum >= this.numPages) {
          return
        }
        this.pageNum++
      },
      cutover() {
        this.confirmSignature()
      },
      // 渲染pdf，到时还会盖章信息，在渲染时，同时显示出来，不应该在切换页码时才显示印章信息
      showpdf(pdfUrl) {
        let caches = JSON.parse(localStorage.getItem('signs')) //获取缓存字符串后转换为对象
        if (caches != null) {
          let datas = caches[this.pageNum]
          if (datas != null && datas != undefined) {
            for (let index in datas) {
              this.addSeal(
                datas[index].sealUrl,
                datas[index].left,
                datas[index].top,
                datas[index].index
              )
            }
          }
        }
        this.canvas = document.getElementById('the-canvas')
        this.ctx = this.canvas.getContext('2d')
        pdfjsLib
          .getDocument({
            url: pdfUrl,
            rangeChunkSize: 65536, // 开启分段加载pdf文件
            disableAutoFetch: false, // false-会自动获取所有分片, true-意味着关闭自动获取
          })
          .promise.then((pdfDoc_) => {
            this.pdfDoc = pdfDoc_
            this.numPages = this.pdfDoc.numPages
            this.renderPage(this.pageNum).then(() => {
              this.renderPdf({
                width: this.canvas.width,
                height: this.canvas.height,
              })
            })
            this.commonSign(this.pageNum, true)
          })
          .catch((error) => {
            console.log(error)
          })
      },
      /**
       *  盖章部分开始
       */
      // 设置绘图区域宽高
      renderPdf(data) {
        this.whDatas = data
        // document.querySelector("#elesign").style.width = data.width + "px";
      },
      // 生成绘图区域
      renderFabric() {
        let canvaEle = document.querySelector('#ele-canvas')
        let pCenter = document.querySelector('.pCenter')
        // canvaEle.height = (this.whDatas.height)*(this.scale);

        // canvaEle.width = pCenter.clientWidth
        canvaEle.width = this.whDatas.width
        canvaEle.height = this.whDatas.height

        // canvaEle.width = 500
        // canvaEle.height = 520

        if(!this.canvasEle){
          this.canvasEle = new fabric.Canvas(canvaEle)
        }

        let container = document.querySelector('.canvas-container')
        container.style.position = 'absolute'
        container.style.top = '60px'
        // container.style.left = "30%";
      },
      // 相关事件操作
      canvasEvents() {
        // 拖拽边界 不能将图片拖拽到绘图区域外
        this.canvasEle.on('object:moving', function(e) {
          var obj = e.target
          // if object is too big ignore
          if (
            obj.currentHeight > obj.canvas.height ||
            obj.currentWidth > obj.canvas.width
          ) {
            return
          }
          obj.setCoords()
          // top-left  corner
          if (obj.getBoundingRect().top < 0 || obj.getBoundingRect().left < 0) {
            obj.top = Math.max(obj.top, obj.top - obj.getBoundingRect().top)
            obj.left = Math.max(obj.left, obj.left - obj.getBoundingRect().left)
          }
          // bot-right corner
          if (
            obj.getBoundingRect().top + obj.getBoundingRect().height >
            obj.canvas.height ||
            obj.getBoundingRect().left + obj.getBoundingRect().width >
            obj.canvas.width
          ) {
            obj.top = Math.min(
              obj.top,
              obj.canvas.height -
              obj.getBoundingRect().height +
              obj.top -
              obj.getBoundingRect().top
            )
            obj.left = Math.min(
              obj.left,
              obj.canvas.width -
              obj.getBoundingRect().width +
              obj.left -
              obj.getBoundingRect().left
            )
          }
        })
      },
      // 添加公章
      addSeal(sealUrl, left, top, index) {
        fabric.Image.fromURL(sealUrl, (oImg) => {
          console.log(oImg, 'oImg------')
          oImg.set({
            left: left,
            top: top,
            index: index,
          })
          oImg.scale(0.5); //图片缩小
          if(this.canvasEle){
            this.canvasEle.add(oImg)
          }
        })
      },
      // 删除签章
      removeSignature() {
        this.canvasEle.remove(this.canvasEle.getActiveObject())
      },
      //翻页展示盖章信息
      commonSign(pageNum, isFirst = false) {
        if (isFirst == false) this.canvasEle.remove(this.canvasEle.clear()) //清空页面所有签章
        let caches = JSON.parse(localStorage.getItem('signs')) //获取缓存字符串后转换为对象
        console.log(caches)
        if (caches == null) return false
        let datas = caches[this.pageNum]
        if (datas != null && datas != undefined) {
          for (let index in datas) {
            this.addSeal(
              datas[index].sealUrl,
              datas[index].left,
              datas[index].top,
              datas[index].index
            )
          }
        }
      },
      //确认签章位置并保存到缓存
      confirmSignature() {
        let data = this.canvasEle.getObjects() //获取当前页面内的所有签章信息
        let caches = JSON.parse(localStorage.getItem('signs')) //获取缓存字符串后转换为对象
        console.log(data, this.whDatas.height, 'data=====')
        let signDatas = {} //存储当前页的所有签章信息
        let i = 0
        for (var val of data) {
          signDatas[i] = {
            width: val.width,
            height: val.height,
            left: val.left,
            top:val.top,
            bottom: this.whDatas.height - val.top - val.width / 2,
            pageNum: this.pageNum,
            sealUrl: this.mainImagelist[val.index],
            // id: this.mainImagelist[val.index].id,
            id: this.mainImagelistIdList[val.index],
            index: val.index,
          }
          i++
        }
        if (caches == null) {
          caches = {}
          caches[this.pageNum] = signDatas
        } else {
          caches[this.pageNum] = signDatas
        }
        localStorage.setItem('signs', JSON.stringify(caches)) //对象转字符串后存储到缓存
        return caches
      },


      //提交数据
      submitSignature() {
        // this.confirmSignature()
        // let caches = localStorage.getItem('signs')
        // console.log(JSON.parse(caches), '提交的数据-------')

        let last = this.confirmSignature()
        console.log('打印last___',last)

        let allPageList = Object.keys(last)  //所有的页码
        let paraList = []  //最后的参数数组
        for(var key in last){
            let value = last[key]  //对应的值
            let coordinate = [] //一个页码下盖的印章
            for(var subkey in value){  //这个页码下所有的数据
              let subValue = value[subkey]
              let subDic = {
                zx:parseInt(subValue.left),
                zy:parseInt(subValue.bottom),
                sealId:subValue.id//标签的id
              }
              coordinate.push(subDic)
            }
            let lastDic = {
              coordinate:coordinate,
              pageNum:parseInt(key)
            }
            paraList.push(lastDic)
        }

        if(paraList.length == 0){
          this.$message.error('请先盖章')
          return
        }

        let myParaDic = {
          fileUrl:this.pdfUrl,
          sealParams:paraList,
        }
        this.loading1 = true
        requestSealStamp(myParaDic).then((res) => {
          if (res.data.code === 200) {
            this.loading1 = false
            let resData = res.data.data
            let passDic = {
              fileName: resData.name,
              fileUrl: resData.link,
              fileSize: resData.fileSize,
              createTime: this.getNowTime(),
              fileType: 8,
              projectType: 3,
              uid:this.fileUid
            }
            localStorage.removeItem('signs') //清除缓存
            this.$emit('handleCloseStamp',passDic)
          }else{
            this.loading1 = false
            this.$message.error(res.data.msg)
          }
        })
      },

      //清空数据
      clearSignature() {
        if(this.canvasEle){
          this.canvasEle.remove(this.canvasEle.clear()) //清空页面所有签章
          localStorage.removeItem('signs') //清除缓存
        }
      },
      end(e) {
        console.log('印章的信息------', e)
        this.addSeal(
          this.mainImagelist[e.newDraggableIndex],
          e.originalEvent.layerX,
          e.originalEvent.layerY,
          e.newDraggableIndex
        )
      },
      //设置PDF预览区域高度
      setPdfArea(val) {
        // this.pdfUrl =
        //   'https://attach-huada.sdhuan.cn/water-conservancy-prod/procedures/2023/01/fe0420a8-9daf-43db-b674-03d5e5b4afc4.pdf'
        this.pdfUrl = val
        this.$nextTick(() => {
          this.showpdf(this.pdfUrl) //接口返回的应该还有盖章信息，不只是pdf
        })
      },
      // 获取当前时间并格式化
      getNowTime(){
          const time = new Date()
          let y = time.getFullYear()
          let m = time.getMonth()+1
          let d = time.getDate()
          let h = time.getHours()
          let mi = time.getMinutes()
          let s = time.getSeconds()
          m = m<10?`0${m}`:m
          d = d<10?`0${d}`:d
          h = h<10?`0${h}`:h
          mi = mi<10?`0${mi}`:mi
          s = s<10?`0${s}`:s
          return `${y}-${m}-${d} ${h}:${mi}:${s}`
      },
      
      // 当前时间
      showTimes() {
        const that = this
        this.timer = setInterval(() => {
          const newDate = new Date() // 修改数据date
          // 获取当前年
          const year = newDate.getFullYear()
          // 获取当前月
          const month = newDate.getMonth() + 1
          // 获取当前日
          const date = newDate.getDate()
          const h = newDate.getHours() // 获取当前小时数(0-23)
          const m = newDate.getMinutes() // 获取当前分钟数(0-59)
          const s = newDate.getSeconds()
          const myDate = new Date()
          const wk = myDate.getDay()
          const weeks = [
            '星期日',
            '星期一',
            '星期二',
            '星期三',
            '星期四',
            '星期五',
            '星期六',
          ]
          const week = weeks[wk]
          that.taskInfo.newDate =
            year +
            '年' +
            this.timeChange(month) +
            '月' +
            this.timeChange(date) +
            '日' +
            ' ' +
            week +
            ' ' +
            this.timeChange(h) +
            ':' +
            this.timeChange(m) +
            ':' +
            this.timeChange(s)
        }, 1000)
      },
      timeChange(s) {
        return s < 10 ? '0' + s : s
      },
    },
    watch: {
      whDatas: {
        handler() {
          const loading = this.$loading({
            lock: true,
            text: 'Loading',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)',
          })
          if (this.whDatas) {
            console.log(this.whDatas)
            loading.close()
            this.renderFabric()
            this.canvasEvents()
            let eleCanvas = document.querySelector('#ele-canvas')
            eleCanvas.style = 'border:1px solid #5ea6ef'
          }
        },
      },
      pageNum: function() {
        this.commonSign(this.pageNum)
        this.queueRenderPage(this.pageNum)
      },
    },
  }
</script>

<style lang="scss" scoped>
  /*pdf部分*/

  .pCenter {
    overflow-x: hidden;
  }

  #the-canvas {
    margin-top: 10px;
  }

  html:fullscreen {
    background: white;
  }

  .elesign {
    display: flex;
    flex: 1;
    flex-direction: column;
    position: relative;
    /* padding-left: 180px; */
    margin: auto;
    min-height: 500px;
    /* width:600px; */
  }

  .page {
    text-align: center;
    margin: 0 auto;
    margin-top: 1%;
  }

  #ele-canvas {
    /* border: 1px solid #5ea6ef; */
    overflow: hidden;
  }

  .ele-control {
    text-align: center;
    margin-top: 3%;
  }

  #page-input {
    width: 7%;
  }

  @keyframes ani-demo-spin {
    from {
      transform: rotate(0deg);
    }

    50% {
      transform: rotate(180deg);
    }

    to {
      transform: rotate(360deg);
    }
  }

  /* .loadingclass{
    position: absolute;
    top:30%;
    left:49%;
    z-index: 99;
} */
  .left {
    position: absolute;
    top: 42px;
    left: -5px;
    padding: 5px 5px;
    /*border: 1px solid #eee;*/
    /*border-radius: 4px;*/
  }

  .left-title {
    text-align: center;
    padding-bottom: 10px;
    border-bottom: 1px solid #eee;
  }

  li {
    list-style-type: none;
    padding: 10px;
  }

  .imgstyle {
    vertical-align: middle;
    width: 100px;
    border: solid 1px #e8eef2;
    // background-image: url('tuo.png');
    background-repeat: no-repeat;
  }

  .right {
    position: absolute;
    top: 7px;
    right: -177px;
    margin-top: 34px;
    padding-top: 10px;
    padding-bottom: 20px;
    width: 152px;
    /*border: 1px solid #eee;*/
    /*border-radius: 4px;*/
  }

  .right-item {
    margin-bottom: 15px;
    margin-left: 10px;
  }

  .right-item-title {
    color: #777;
    height: 20px;
    line-height: 20px;
    font-size: 12px;
    font-weight: 400;
    text-align: left !important;
  }

  .detail-item-desc {
    color: #333;
    line-height: 20px;
    width: 100%;
    font-size: 12px;
    display: inline-block;
    text-align: left;
  }

  .btn-outline-dark {
    color: #0f1531;
    background-color: transparent;
    background-image: none;
    border: 1px solid #3e4b5b;
  }

  .btn-outline-dark:hover {
    color: #fff;
    background-color: #3e4b5b;
    border-color: #3e4b5b;
  }

  .item {
    cursor: pointer;
  }

  .avue-dialogs {
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999999991;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
</style>
